package netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;


/**
 * @author 帅小伙
 * @date 2022/1/16
 * @description
 * 1.SimpleChannelInboundHandler  是  ChannelInboundHandlerAdapter的子类
 * 2.HttpObject   表示客户端和服务器端  相互通信的数据被封装成  httpObject
 */
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    /*
    *  读取客户端数据
    * */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        // 判断是否是 HeepRequest请求
        if(msg instanceof HttpRequest) {

            System.out.println("连接的pipeline"+ctx.pipeline().hashCode());
            HttpRequest httpRequest = (HttpRequest)msg;

             // 对特定资源进行过滤
             //获取uri
            URI uri = new URI(httpRequest.uri());
            if("/favicon.ico".equals(uri.getPath())){
                System.out.println("请求了http://127.0.0.1:6969/favicon.ico");
                return;
            }
            System.out.println("msg类型= "+msg.getClass());
            System.out.println("客户端的地址 "+ctx.channel().remoteAddress());

            //回复信息给浏览器
            ByteBuf content = Unpooled.copiedBuffer("hello ", CharsetUtil.UTF_8);

            //构造一个 httpResponse
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, content);
            // 设置响应头  文本类型 和 长度
            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,content.readableBytes());
            ctx.writeAndFlush(response);
        }
    }
}
